package cn.fws.meap.weiChatWeb;

import cn.fws.framework.utils.StringUtils;
import cn.fws.framework.utils.UUIDUtils;
import cn.fws.meap.community.vo.Result;
import cn.fws.meap.user.entity.User;
import cn.fws.meap.user.service.IUserService;
import cn.fws.meap.utils.WechatUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Arrays;

import org.apache.http.client.ClientProtocolException;


@RestController
@Api(tags = "小程序调用接口")
public class WeiChatController {
    @Autowired
    private IUserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation(value = "从微信中获取openid,和session_key")
    @ApiImplicitParams(@ApiImplicitParam(value = "code", dataType = "String"))
    @GetMapping("/weiChat/openid")
    public Result test(String code) throws ClientProtocolException, IOException {
        //获取"session_key":和"openid"
        JSONObject jsonObject = WechatUtils.doGet(code);

        //从数据库中查一下user用户中有没有这个openid
        User user = userService.selectByOpenId(jsonObject.getString("openid"));
        //如果没有就生成一个userId
        if (StringUtils.isNull(user)) {

            //设置userId返回给前台数据
            String userId = UUIDUtils.getUUID();
            redisTemplate.opsForValue().set("userId"+userId,userId);
            redisTemplate.opsForValue().set("openid"+userId,jsonObject.getString("openid"));
            return new Result(true, userId, true, null, null,null);
        } else {
        	String userId = user.getId();
        	String nickname = user.getNickname();
        	String userImgKey = user.getUserImgKey();
            String isBind = user.getIsBind();
            System.out.println("首次登陆isBind+"+user.toString());
            return new Result(true, userId, false, nickname, userImgKey,isBind);
        }
    }

    public static void main(String[] args) {
        Arrays.asList( "a", "b", "d" ).forEach(e -> System.out.println( e ) );


    }

}
